package com.petruisfan.banimei;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A dummy fragment representing a section of the app.
 */
public class TabFragment extends Fragment {
	public static final String ARG_SECTION_NUMBER = "section_number";
	private RecordsDbAdapter rDbAdapter = null; 
	
	private SparseArray<String> row_content_by_id = new SparseArray<String>();
	
	public TabFragment() {
	}
	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	View result = new RelativeLayout(getActivity());
    	
        TextView textView = new TextView(getActivity());
        textView.setGravity(Gravity.CENTER);
        
        Bundle args = getArguments();
        int section_nr = args.getInt(ARG_SECTION_NUMBER);
        
        rDbAdapter = new RecordsDbAdapter();
        switch (section_nr) {
        case 1:
        	result = (RelativeLayout) inflater.inflate(R.layout.add_layout, container, false);
        	
        	// Get a reference to the AutoCompleteTextView in the layout
        	AutoCompleteTextView record_text = (AutoCompleteTextView) result.findViewById(R.id.pay_name);
        	// Get the string array
        	String[] records = rDbAdapter.getRecordNames();
        	// Create the adapter and set it to the AutoCompleteTextView 
        	ArrayAdapter<String> adapter = 
        	        new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, records);
        	record_text.setAdapter(adapter);
        	
        	break;
        case 2:
        	result = (RelativeLayout) inflater.inflate(R.layout.total_layout, container, false);
        	TextView total = (TextView)result.findViewById(R.id.total_spent);
        	total.setText(rDbAdapter.getSum());
        	break;
        case 3:
        	result = inflater.inflate(R.layout.records_layout, container, false);
    	    fillTable(result);
        	break;
        }
        
        return result;
    }


	private void fillTable(View result) {
		TableLayout table = (TableLayout)(result.findViewById(R.id.records_table));
		
		Cursor cursor = rDbAdapter.fetchAllRecords();
		cursor.moveToFirst();
		
		TableRow row = new TableRow(getActivity());
		
		//
		// Add headers
		//
		for (int i=1; i<4; i++) {
			addHeader(cursor.getColumnName(i), row);
		}
		
//		addHeader("", row);
		
		table.addView(row);
		
		if (cursor.isAfterLast()) {
			return;
		}
		do {
			row=new TableRow(getActivity());
			
			for (int i=1; i<4; i++) {
				addCell(cursor.getString(i), row);
			}
			
//			CheckBox checkBox = new CheckBox(getActivity());
//			checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//			    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//			        if ( isChecked ) {
//			            Toast.makeText(getActivity(), "checked", Toast.LENGTH_SHORT).show();
//			        }
//			    }
//			});
//			row.addView(checkBox);
			
			row.setOnLongClickListener(new View.OnLongClickListener() {
			    // Called when the user long-clicks on someView
				@Override
			    public boolean onLongClick(final View view) {
			    	PopupMenu popup = new PopupMenu(getActivity(), view);
			    	popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
						
						@Override
						public boolean onMenuItemClick(MenuItem item) {
							switch (item.getItemId()) {
				            case R.id.row_menu_delete:
				            	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				            	    @Override
				            	    public void onClick(DialogInterface dialog, int which) {
				            	        switch (which){
				            	        case DialogInterface.BUTTON_POSITIVE:
				            	        	rDbAdapter.deleteRecord(view.getId());
				            	        	Toast.makeText(getActivity(), "Row deleted", Toast.LENGTH_SHORT).show();
				            	        	Utils.refreshTotal( (TextView)getActivity().findViewById(R.id.total_spent) );

				            	        	((TableLayout)view.getParent()).removeView(view);
				            	        	break;

				            	        case DialogInterface.BUTTON_NEGATIVE:
				            	            //No button clicked
				            	            break;
				            	        }
				            	    }
				            	};
				            	
				            	AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				            	builder.setMessage("Delete " + row_content_by_id.get(view.getId()) + "?").setPositiveButton("Yes", dialogClickListener)
				            	    .setNegativeButton("No", dialogClickListener).show();
				            	
				                return true;
				            default:
				            	return false;
							}
						}
						
					});
			    	
			        MenuInflater inflater = popup.getMenuInflater();
			        inflater.inflate(R.menu.row_menu, popup.getMenu());
			        popup.show();
			        
			        return true;
			    }
			    
			});

			int id = cursor.getInt(0);
			row.setId(id);
			row_content_by_id.put(id, cursor.getString(1) + "/" + cursor.getString(2));
			table.addView(row);
			
			cursor.moveToNext();
		} while (! cursor.isAfterLast());
		
		cursor.close();
	}


	private void addCell(String text, TableRow row ) {
		TextView recordCell = new TextView(getActivity());
		recordCell.setTextSize(19);
//		recordCell.setBackgroundColor(Color.WHITE);
		recordCell.setText(text);
		row.addView(recordCell);
	}
	
	private void addHeader (String text, TableRow row ) {
		TextView recordCell = new TextView(getActivity());
		recordCell.setTextSize(23);
		recordCell.setTypeface(null, Typeface.BOLD);
		recordCell.setBackgroundColor(getResources().getColor(R.color.banimei));
		recordCell.setTextColor(Color.WHITE);
		recordCell.setText(text);
		
		row.addView(recordCell);
	}
}
